<?php

namespace app\api\controller;

use app\common\model\Manager;
use app\common\model\SysSetting;
use app\common\logic\Auth;
use app\common\model\UserSetting;
use app\common\RedisCache;
use think\facade\Validate;
use app\common\service\QlRedis;
use app\common\service\Wwork;
use app\common\Verify;
use app\lib\Result;

class Sign extends \app\BaseController
{
  protected $redis;
  public function initialize()
  {
    $this->redis = new QlRedis();
  }
  public function login()
  {
    $type = input('param.type');
    if ($type == 'wx_login') {
      return self::wechat_login($this->redis);
    } elseif ($type == 'ww_login') {
      return self::ww_login($this->redis);
    }
    if (request()->isPost()) {
      $ip = get_client_ip();
      $rule = [
        'username|用户名/手机号' => 'min:5',
        'password|密码' => 'min:8|max:26',
        'phone|手机号' => 'mobile',
        'captcha|验证码' => 'number',
      ];
      $data = [
        'token'  => input('param.token', '', 'trim'),
        'cid'  => input('param.cid', '', 'trim'),
        'username'  => input('param.username/s', '', 'trim'),
        'password'  => input('param.password', '', 'trim'),
        'phone'  => input('param.mobile/s', '', 'trim'),
        'captcha'  => input('param.captcha/s', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return Result::Error($validate->getError());
      }
      // if (!checkphone($data['username'])) {
      //   return Result::Error('手机号格式不正确');
      // }
      if (empty($data['username']) && empty($data['password']) && empty($data['phone']) && empty($data['captcha'])) {
        return Result::Error('登录信息不能都为空');
      }
      $opData['title'] = '管理登录';
      $time = time();
      if (!empty($data['username']) && !empty($data['password'])) {
        $data['token'] = is_array($data['token']) ? json_encode($data['token'], true) : $data['token'];
        $dataVerify['token'] = base64_encode($data['token']);
        $dataVerify['captcha_id'] = '4960354834839720';
        Verify::check($dataVerify);
        $hasUser = Manager::field('id,salt,password,phone,login_times,is_admin,groupId,status,username,avatar,version,version_end_time,wechat_open_id')->where('phone|username', $data['username'])->find();
        if (empty($hasUser)) {
          $opData['uid'] = 0;
          $opData['username'] = $data['username'];
          $opData['ext_log'] = '查询不到用户';
          $opData['opstatus'] = -1;
          addOpLog($opData);
          $limitResult = limitResult('managerlogin', $ip);
          if ($limitResult['code'] != -1) {
            return Result::Error('帐号或密码不正确');
          } else {
            return Result::Error($limitResult['msg']);
          }
        }
        if ($hasUser['status'] != 1) {
          return Result::Error('用户状态异常或被封禁，请联系管理进行处理。');
        }
        $saltPassword = md5($data['password'] . $hasUser['salt']);
        if ($saltPassword != $hasUser['password']) {
          $opData['uid'] = (int) $hasUser['id'];
          $opData['username'] = $data['username'];
          $opData['ext_log'] = '登录密码错误，错误密码为：' . $data['password'];
          $opData['opstatus'] = -1;
          addOpLog($opData);
          $limitResult = limitResult('managerlogin', $ip);
          if ($limitResult['code'] != -1) {
            return Result::Error('帐号或密码不正确，请确认后重新登录');
          } else {
            return Result::Error($limitResult['msg']);
          }
        }
      } else {
        $hasUser = Manager::field('id,salt,password,phone,login_times,is_admin,groupId,status,username,avatar,version,version_end_time,wechat_open_id')->where('phone', $data['phone'])->find();
        if (empty($hasUser)) {
          $opdata['uid'] = 0;
          $opdata['username'] = $data['phone'];
          $opdata['ext_log'] = $data['phone'] . '未注册，无法登录';
          $opdata['opstatus'] = -1;
          addOpLog($opdata);
          $limitResult = limitResult('managerlogin', $ip);
          if ($limitResult['code'] != -1) {
            return Result::Error('该手机号未注册');
          } else {
            return Result::Error($limitResult['msg']);
          }
        }
        $sms_code = $this->redis->get('smsCode:' . $data['phone']);
        if (empty($sms_code) || ($sms_code != $data['captcha'])) {
          return Result::Error('验证码已过期或不存在，请重新获取！');
        }
        $this->redis->del('smsCode:' . $data['phone']);
      }
      //更新会员状态
      $param = [
        'login_times' => $hasUser['login_times'] + 1,
        'login_ip' => $ip,
        'login_time' => $time,
      ];
      if (!empty($data['cid'])) {
        $param['cid'] = $data['cid'];
      }
      $opData['uid'] = (int) $hasUser['id'];
      $opData['username'] = $hasUser['phone'];
      $opData['ext_log'] = '登录成功';
      $opData['opstatus'] = 1;
      addOpLog($opData);
      Manager::where('id', $hasUser['id'])->update($param);
      $payload['uid']       = $hasUser['id'];
      $payload['password']       = $hasUser['password'];
      $payload['loginTime'] = $time;
      $payload['refresh_key'] = createId();
      $rules = Auth::getRuleId($hasUser['groupId']);
      $tokenArr['rules'] = Auth::getRuleKey($rules);
      $token = think_encrypt(json_encode($payload));
      $tokenArr['userToken'] = $token;
      //用户登录有效期
      $loginRefreshExpireTime = config('app.SYS_STATIC.login_refresh_expire');
      $loginExpireTime = config('app.SYS_STATIC.login_expire');
      // 存储用户刷新token
      $this->redis->set('token-' . $hasUser['id'], $token, $loginExpireTime);
      $this->redis->set('refresh:key:' . $payload['refresh_key'], json_encode($payload), $loginRefreshExpireTime);
      $tokenArr['Expire'] = $loginRefreshExpireTime * 1000;
      $tokenArr['loginExpire'] = ($loginExpireTime + $time) * 1000;
      $tokenArr['isSuper'] = $hasUser['is_admin'];
      $tokenArr['username'] = $hasUser['username'];
      $tokenArr['avatar'] = empty($hasUser['avatar']) ? 'https://img.alicdn.com/imgextra/i2/573804794/O1CN014HgKAE1lHhcQzowB3_!!573804794.png' : $hasUser['avatar'];
      if ($hasUser['version_end_time'] > 0) {
        $tokenArr['version_end_time'] = date('Y-m-d', $hasUser['version_end_time']);
      } else {
        $tokenArr['version_end_time'] = '';
      }
      if ($hasUser['version'] > 0) {
        $version = (new RedisCache())->getVersionInfo($hasUser['version']);
        $tokenArr['version_title'] = $version['title'];
      } else {
        $tokenArr['version_title'] = '未知';
      }
      $hasSetting = UserSetting::where('uid', $hasUser['id'])->find();
      if (empty($hasSetting)) {
        $settingData['dev_key'] = createULId('DEV-');
        $settingData['uid'] = $hasUser['id'];
        $settingData['username'] = $hasUser['username'];
        UserSetting::insert($settingData);
      }
      $device = request()->header('Device');
      $tplData['thing10'] = '账号密码登录(浏览器)';
      if (!empty($device)) {
        $tplData['thing10'] = '账号密码登录(APP)';
      }
      $tplData['time3'] = date('Y-m-d H:i:s');
      $tplData['thing4'] = '柠聚开发平台';
      $tplData['thing6'] = $hasUser['username'];
      $tplData['character_string7'] = $ip;
      if (isset($hasUser['wechat_open_id']) && !empty($hasUser['wechat_open_id'])) {
        sendTemplateMsgLY($hasUser['wechat_open_id'], 'gH828dwx5oj2Wdd50IBKygKn9RKpGL1djMtUsTynAxo', json_encode($tplData));
      }
      checkIsHasInviter($hasUser['id']);
      return Result::Success($tokenArr, '登录成功，页面将自动跳转……');
    }
    return Result::Error('请求不正常');
  }
  public function get_wechat_login_qrcode()
  {
    $uuid = createId();
    (new RedisCache)->getSetQrcodeLoginUUID($uuid, 1, 120);
    $data = getWxQrcode('ldp::' . $uuid);
    if (empty($data)) {
      return json(['code' => -1, 'msg' => '二维码获取失败']);
    }
    $return['qrcode'] = $data['qrcode_pic'];
    $return['url'] = $data['url'];
    $token = think_encrypt($uuid);
    $return['token'] = $token;
    $return['room'] = 'qrcode_login';
    $return['union_id'] = $uuid;
    return json(['code' => 200, 'msg' => 'success', 'data' => $return]);
  }
  public function getWxLoginStatus()
  {
    $uuid = input('param.token');
    if (empty($uuid)) {
      return json(['code' => 200, 'msg' => '必要参数不能为空', 'cd' => 0]);
    }
    $uuid = think_decrypt($uuid);
    $uuidStr = (new RedisCache)->getSetQrcodeLoginUUID($uuid);
    if (empty($uuidStr)) {
      return json(['code' => 200, 'msg' => '扫码超时，请刷新后重试' . $uuid, 'cd' => -99]);
    }
    if ($uuidStr == 1) {
      return json(['code' => 200, 'msg' => '等待扫描', 'cd' => 0]);
    }
    if ($uuidStr == -3) {
      return json(['code' => 200, 'msg' => '您还未绑定平台会员账号，请先登录绑定后再试', 'cd' => -3]);
    }
    $uuidStr = json_decode($uuidStr, true);
    if (!empty($uuidStr)) {
      return json(['code' => 200, 'msg' => '登录成功', 'data' => $uuidStr, 'cd' => 200]);
    } else {
      return json(['code' => 200, 'msg' => '扫码超时，请刷新后重试', 'cd' => -2]);
    }
  }
  // 使用带参数二维码扫码登录接口
  public function wechat_login()
  {
    $ip = get_client_ip();
    if (request()->isPost()) {
      $rule = [
        'event_key'  => 'require',
        'open_id'  => 'require',
      ];
      $data = [
        'event_key'  => input('param.event_key', '', 'trim'),
        'open_id'  => input('param.open_id', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return Result::Success(['content' => $validate->getError()], 'fail');
      }
      $event_key = $data['event_key'];
      $open_id = $data['open_id'];
      $event_key = str_replace('ldp::', '', $event_key);
      if (empty($open_id)) {
        return Result::Success(['content' => '必要参数为空'], 'fail');
      }
      $opData['title'] = '管理登录';
      $time = time();
      $hasUser = Manager::where('wechat_open_id', $open_id)->find();
      if (empty($hasUser)) {
        $opData['uid'] = 0;
        $opData['username'] = $open_id;
        $opData['ext_log'] = '[微信授权]查询不到用户';
        $opData['opstatus'] = -1;
        addOpLog($opData);
        $limitResult = limitResult('managerlogin', $ip);
        if ($limitResult['code'] != -1) {
          (new RedisCache)->getSetQrcodeLoginUUID($event_key, -3, 120);
          return Result::Success(['content' => '您还未绑定平台账号，请【使用账号密码】登录平台并绑定后再试'], 'fail');
        } else {
          return Result::Success(['content' => $limitResult['msg']], 'fail');
        }
      }
      if ($hasUser['status'] != 1) {
        return Result::Success(['content' => '用户状态异常或被封禁，请联系上级管理进行处理。'], 'fail');
      }
      //更新会员状态
      $param = [
        'login_times' => $hasUser['login_times'] + 1,
        'login_ip' => $ip,
        'login_time' => $time,
      ];
      $opData['uid'] = (int) $hasUser['id'];
      $opData['username'] = $hasUser['phone'];
      $opData['ext_log'] = '登录成功';
      $opData['opstatus'] = 1;
      addOpLog($opData);
      Manager::where('id', $hasUser['id'])->update($param);
      $payload['uid']       = $hasUser['id'];
      $payload['password']       = $hasUser['password'];
      $payload['loginTime'] = $time;
      $payload['refresh_key'] = createId();
      $rules = Auth::getRuleId($hasUser['groupId']);
      $tokenArr['rules'] = Auth::getRuleKey($rules);
      $token = think_encrypt(json_encode($payload));
      $tokenArr['userToken'] = $token;
      if ($hasUser['version_end_time'] > 0) {
        $tokenArr['version_end_time'] = date('Y-m-d', $hasUser['version_end_time']);
      } else {
        $tokenArr['version_end_time'] = '';
      }
      if ($hasUser['version'] > 0) {
        $version = (new RedisCache())->getVersionInfo($hasUser['version']);
        $tokenArr['version_title'] = $version['title'];
      } else {
        $tokenArr['version_title'] = '未知';
      }
      //用户登录有效期
      $loginExpireTime = config('app.SYS_STATIC.login_expire');
      $loginRefreshExpireTime = config('app.SYS_STATIC.login_refresh_expire');
      // 存储用户token
      $this->redis->set('token-' . $hasUser['id'], $token, $loginExpireTime);
      $this->redis->set('refresh:key:' . $payload['refresh_key'], json_encode($payload), $loginRefreshExpireTime);
      $tokenArr['Expire'] = $loginExpireTime * 1000;
      $tokenArr['isSuper'] = $hasUser['is_admin'];
      $tokenArr['username'] = $hasUser['username'];
      $tokenArr['avatar'] = $hasUser['avatar'];
      (new RedisCache)->getSetQrcodeLoginUUID($event_key, json_encode($tokenArr, true));
      socketServerPush('SI4924539635987626', 'qrcode_login', json_encode(['data' => $tokenArr, 'cd' => 200], true), 1, $event_key);
      $tplData['time3'] = date('Y-m-d H:i:s');
      $tplData['thing10'] = '微信扫码登录';
      $tplData['thing4'] = '柠聚开发平台';
      $tplData['thing6'] = $hasUser['username'];
      $tplData['character_string7'] = '127.0.0.1';
      sendTemplateMsgLY($open_id, 'gH828dwx5oj2Wdd50IBKygKn9RKpGL1djMtUsTynAxo', json_encode($tplData));
      return Result::Success();
    }
    return Result::Success(['content' => '请求不正常'], 'fail');
  }
  private static function ww_login($redis)
  {
    $ip = get_client_ip();
    if (request()->isPost()) {
      $rule = [
        'code'  => 'require',
      ];
      $data = [
        'code'  => input('param.code', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return Result::Error($validate->getError());
      }
      $data = (new Wwork)->getUserInfo($data['code']);
      $opData['title'] = '管理登录';
      $time = time();
      $hasUser = Manager::field('id,salt,password,phone,login_times,is_admin,groupId,status,username,avatar')->where('ww_user_id', $data['UserId'])->find();
      if (empty($hasUser)) {
        $opData['uid'] = 0;
        $opData['username'] = $data['UserId'];
        $opData['ext_log'] = '[企业微信授权]查询不到用户';
        $opData['opstatus'] = -1;
        addOpLog($opData);
        $limitResult = limitResult('managerlogin', $ip);
        if ($limitResult['code'] != -1) {
          return Result::Error('未绑定平台账号');
        } else {
          return Result::Error($limitResult['msg']);
        }
      }
      if ($hasUser['status'] != 1) {
        return Result::Error('用户状态异常或被封禁，请联系上级管理进行处理。');
      }
      if (empty($hasUser['avatar'])) {
        $param['avatar'] = $hasUser['avatar'] = $data['headimgurl'];
      }
      //更新会员状态
      $param = [
        'login_times' => $hasUser['login_times'] + 1,
        'login_ip' => $ip,
        'login_time' => $time,
      ];
      $opData['uid'] = (int) $hasUser['id'];
      $opData['username'] = $hasUser['phone'];
      $opData['ext_log'] = '登录成功';
      $opData['opstatus'] = 1;
      addOpLog($opData);
      Manager::where('id', $hasUser['id'])->update($param);
      $payload['uid']       = $hasUser['id'];
      $payload['password']       = $hasUser['password'];
      $payload['loginTime'] = $time;
      $payload['refresh_key'] = createId();
      $rules = Auth::getRuleId($hasUser['groupId']);
      $tokenArr['rules'] = Auth::getRuleKey($rules);
      $token = think_encrypt(json_encode($payload));
      $tokenArr['userToken'] = $token;
      //用户登录有效期
      $loginExpireTime = config('app.SYS_STATIC.login_expire');
      $loginRefreshExpireTime = config('app.SYS_STATIC.login_refresh_expire');
      // 存储用户token
      $redis->set('token-' . $hasUser['id'], $token, $loginExpireTime);
      $redis->set('refresh:key:' . $payload['refresh_key'], json_encode($payload), $loginRefreshExpireTime);
      $tokenArr['Expire'] = $loginExpireTime * 1000;
      $tokenArr['isSuper'] = $hasUser['is_admin'];
      $tokenArr['username'] = $hasUser['username'];
      $tokenArr['avatar'] = $hasUser['avatar'];
      return Result::Success($tokenArr, '登录成功，页面将自动跳转……');
    }
    return Result::Error('请求不正常');
  }
  public function getLoginParam()
  {
    $setting = SysSetting::where('id', 1)->find();
    $return['wechat_login'] = 0;
    $return['oauth_login'] = 0;
    $return['captcha'] = $setting['captcha_type'];
    if (!empty($setting['wechat_appid']) && !empty($setting['wechat_secret'])) {
      $return['wechat_login'] = 1;
      $return['oauth_login'] = 1;
      $return['wechat_appid'] = $setting['wechat_appid'];
    }
    if (!empty($setting['ww_appid']) && !empty($setting['ww_agentid'])) {
      $return['ww_login'] = 1;
      $return['oauth_login'] = 1;
      $return['ww_appid'] = $setting['ww_appid'];
      $return['ww_agentid'] = $setting['ww_agentid'];
    }
    if ($setting['captcha_type'] == 'dragon') {
      $return['captcha_app_id'] = $setting['dragon_captcha_id'];
    } else if ($setting['captcha_type'] == 'tencent') {
      $return['captcha_app_id'] = $setting['tenc_capt_app_id'];
    }
    return Result::Success($return);
  }
  public function logout()
  {
    $getUserToken = request()->header('Authorization');
    if (!empty($getUserToken)) {
      $userTokenArray = explode(':', $getUserToken);
      $getUserToken = $userTokenArray[0];
      $getUserToken = explode(' ', $getUserToken);
      $getUserToken = $getUserToken[1];
      $userToken = think_decrypt($getUserToken);
      $payload   = json_decode($userToken, true);
      if (isset($payload['uid'])) {
        $this->redis->del('token-' . $payload['uid']);
        $this->redis->del('refresh:key:' . $payload['refresh_key']);
      }
    }
    return Result::Success([], '退出成功');
  }
}
